package com.foolishbird.sdk.ui.fragment;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.foolishbird.sdk.api.FBSDK;
import com.foolishbird.sdk.core.HttpEngineApi;
import com.foolishbird.sdk.params.FloatKefuResponseParams;
import com.foolishbird.sdk.params.ResponseParams;
import com.foolishbird.sdk.params.bean.FloatKefu;
import com.foolishbird.sdk.params.bean.FloatMenu;
import com.foolishbird.sdk.params.bean.FloatUserInfo;
import com.foolishbird.sdk.params.bean.State;
import com.foolishbird.sdk.ui.activity.FoolishBirdFloatExtensionActivity;
import com.foolishbird.sdk.ui.assist.OnFinishActivityListener;
import com.foolishbird.sdk.ui.view.DialogFactory;
import com.foolishbird.sdk.utils.MyFragmentManger;
import com.foolishbird.sdk.utils.ResUtils;
import com.foolishbird.sdk.utils.ToolsUtils;
import com.foolishbird.sdk.utils.WL;
import com.squareup.picasso.Picasso;

import java.util.HashMap;


public class FloatWebFragment extends BaseHttpFragment implements View.OnClickListener {
private final String TAG = FloatWebFragment.class.getSimpleName();

//    private LinearLayout phoneLayout,realnameLayout,versionLayout,pwdLayout;
    private TextView titleTxt;
    private ImageView backView;
    private WebView mContentWebView;
    private ProgressBar mContentProgressBar;
    private static final String QQ_CUSTOMER_SERVICE = "http://wpd.b.qq.com/page/webchat.html";
    private static final String WECHAT_PUBLIC_NUMBER = "http://www.51wansy.sdkv3.com/";

    private final HashMap<String, String> mLoadUrlStack = new HashMap<String, String>();

    public static final FloatWebFragment newInstance(Bundle bundle) {
        FloatWebFragment fragment = new FloatWebFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

//    @Override
//    public void onPause() {
//        super.onStop();
//        if("正在前往微信".equals(menu.getName())){
//            MyFragmentManger.getInstance().goBack(this);
//        }
//    }



    FloatMenu menu;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        int resource = ResUtils.getLayoutIdentifier(getActivity(), "fb_fragment_float_web");
        View contentView =inflater.inflate(resource,null);
        titleTxt = contentView.findViewById(getViewIdentifier("fb_fragment_float_title"));

        backView = contentView.findViewById(getViewIdentifier("fb_fragment_login_back"));
        backView.setOnClickListener(this);
        mContentProgressBar = (ProgressBar) contentView.findViewById(getViewIdentifier("activity_extendsionbar_content_progressbar"));

        mContentWebView = (WebView) contentView.findViewById(getViewIdentifier("activity_extendsionbar_content_webview"));
        WebSettings webSettings = mContentWebView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setSupportZoom(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mContentWebView.setWebChromeClient(new ExtensionBarWebChromeClient());
        mContentWebView.setWebViewClient(new ExtensionBarWebViewClient());
        mContentWebView.loadUrl("");
        menu =(FloatMenu)getArguments().getSerializable("menu");
         String append=menu.getLink().contains("?")?"&":"?";
         append+="token="+HttpEngineApi.getInstance().getEngineConduits().readCurrentLoginUserTicket()
                 +"&game_id="+ FBSDK.getInstance().getGameId();

        mContentWebView.loadUrl(menu.getLink()+append);
        titleTxt.setText(menu.getName());


//        HttpEngineApi.getInstance().getKefuInfo(requestCallbackHandler(FloatKefuResponseParams.class));
        return contentView;

    }

    private FloatUserInfo userInfo;

    private class ExtensionBarWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);


        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mContentProgressBar != null) {
                if (newProgress == 100) {
                    mContentProgressBar.setVisibility(View.GONE);
                } else {
                    if (View.VISIBLE != mContentProgressBar.getVisibility()) {
                        mContentProgressBar.setVisibility(View.VISIBLE);
                    }
                    mContentProgressBar.setProgress(newProgress);
                }

            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private class ExtensionBarWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            WL.d(TAG, "shouldOverrideUrlLoading ---->url: " + url);

            if (url.startsWith(QQ_CUSTOMER_SERVICE)) {
                try {
                    String qq = getValueByName(url, "nameAccount");

                    WL.d(TAG, "shouldOverrideUrlLoading ---->qq: " + qq);

                    String localUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(localUrl)));
                } catch (ActivityNotFoundException e) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                }
            } else if (url.startsWith(WECHAT_PUBLIC_NUMBER)) {
                if (ToolsUtils.isInstallWeixin(getActivity().getApplicationContext())) {
                    String originalAppId = getValueByName(url, "id");
                    String appId = getValueByName(url, "appId");

                    ToolsUtils.startWeChatPublicNumber(getActivity().getApplicationContext(), appId, originalAppId);
                } else {
                    String message = getString(getStringIdentifier("hnssn_hint_wechat_uninstall"));
                    DialogFactory.createConfirmDialog(getActivity(), message).show();
                }
            }else if (url.startsWith("weixin://")){
                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)),123);
            }
            else {
                if (mContentWebView != null) {
                    mContentWebView.loadUrl(url);
                }


            }

            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            WL.d(TAG, "onPageFinished ----> url: " + url);
            mLoadUrlStack.put(url, url);
            MyFragmentManger.getInstance().goBack(FloatWebFragment.this);
//            mLoadUrlStack.push(url);
//            if (mLoadUrlStack.isEmpty()) {
//                mContentWebViewGoback.setVisibility(View.GONE);
//            } else {
//                mContentWebViewGoback.setVisibility(View.VISIBLE);
//            }
        }
    }

    public static String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }

    @Override
    public void onClick(View view) {
        if(view == backView){
            if(mLoadUrlStack.size()<=2){
                mContentWebView.goBack();
                mLoadUrlStack.remove(mContentWebView.getUrl());
                mContentWebView.clearHistory();
                mContentWebView.clearCache(true);
                CookieManager.getInstance().removeAllCookies(null);
                CookieManager.getInstance().flush();
//                contentLayout.setVisibility(View.GONE);
                MyFragmentManger.getInstance().goBack(this);
            }else{
                mContentWebView.goBack();
                mLoadUrlStack.remove(mContentWebView.getUrl());
            }

        }
    }

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);

        WL.d("FloatNoticeFragment",response.toString());
    }

    private OnFinishActivityListener getOnFinishActivityListener() {
        if (!isNullContext()) {
            Activity activity = getActivity();
            if (activity instanceof OnFinishActivityListener) {
                return (OnFinishActivityListener) activity;
            }
        }
        return null;
    }
}
